package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class MiniBootstrap {
    private ServerConfiguration configuration;

    private Engine engine;

    private Connector connector;

    private void init() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        //读取配置类
        configuration = parseServerConfiguration();

        //初始化引擎
        engine = new Engine(configuration.getAppBase());
        engine.init();

        //初始化连接器
        connector = new Connector(configuration.getConnectorPort(), engine);
        connector.init();
    }

    private void start() throws IOException {
        engine.start();
        connector.start();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        MiniBootstrap bootstrap = new MiniBootstrap();

        bootstrap.init();
        bootstrap.start();
    }

    private ServerConfiguration parseServerConfiguration() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        ServerConfiguration configuration = new ServerConfiguration();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//Connector");
            String port = selectNodes.get(0).attributeValue("port");
            configuration.setConnectorPort(port);

            selectNodes = rootElement.selectNodes("//Host");
            String appBase = selectNodes.get(0).attributeValue("appBase");
            configuration.setAppBase(appBase);

          } catch (DocumentException e) {
             e.printStackTrace();
             return null;
          }

          return configuration;
    }

}
